package com.aaa.distincklock.service;

import com.aaa.distincklock.dao.StockDao;
import com.aaa.distincklock.entity.Stock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @author:LiWei
 * @date:2022年12月08日16:59
 */
@Service
public class StockService_redisson {

    @Autowired
    private StockDao stockDao;
    @Autowired
    private RedissonClient redisson;
    //减库存
    public String decrement(Integer productid) {
        //获取锁对象
        RLock lock = redisson.getLock("product::" + productid);
        //锁定时间
        lock.lock(30, TimeUnit.SECONDS);
        try {
            //查找指定商品的库存
            Stock stock = stockDao.selectById(productid);
            //判断是否大于0
            if (stock.getStock() > 0) {
                //减库存
                stock.setStock(stock.getStock() - 1);
                stockDao.updateById(stock);
                System.out.println("商品编号为:" + productid + "的商品库存剩余:" + stock.getStock() + "个");
                return "商品编号为:" + productid + "的商品库存剩余:" + stock.getStock() + "个";
            } else {
                System.out.println("商品编号为:" + productid + "的商品库存不足。");
                return "商品编号为:" + productid + "的商品库存不足。";
            }
        } finally {
            //释放锁
            lock.unlock();
        }


    }
}
